package app

import (
	"context"
	"goldtree/internal"
	"goldtree/internal/service"

	"github.com/gogf/gf/v2/frame/g"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// OnStartup is called when the app starts and the context is available
func (a *App) OnStartup(ctx context.Context) {
	a.ctx = ctx
	g.Log().Info(ctx, "Wails应用正在启动...")

	// 初始化数据库
	if err := internal.InitDB(ctx); err != nil {
		g.Log().Error(ctx, "数据库初始化失败:", err)
		return
	}
	g.Log().Info(ctx, "数据库初始化完成")

	// 初始化系统数据
	if err := service.Init.InitializeSystem(ctx); err != nil {
		g.Log().Warning(ctx, "系统数据初始化失败:", err)
	}
	g.Log().Info(ctx, "系统数据初始化完成")

	g.Log().Info(ctx, "Wails应用启动完成")
}

// OnDomReady is called after front-end resources have been loaded
func (a *App) OnDomReady(ctx context.Context) {
	g.Log().Info(ctx, "前端资源加载完成")
}

// OnBeforeClose is called when the application is about to quit,
// either by clicking the window close button or calling runtime.Quit.
func (a *App) OnBeforeClose(ctx context.Context) (prevent bool) {
	g.Log().Info(ctx, "应用即将关闭")
	return false
}

// OnShutdown is called when the application is shutting down
func (a *App) OnShutdown(ctx context.Context) {
	g.Log().Info(ctx, "应用正在关闭...")
}

// ========== API Bridge Methods ==========

// GetAppInfo 获取应用信息
func (a *App) GetAppInfo() map[string]interface{} {
	return map[string]interface{}{
		"name":        "GoldTree",
		"version":     "1.0.0",
		"description": "股票量化交易管理系统",
		"mode":        "desktop",
	}
}

// GetSystemStats 获取系统统计信息
func (a *App) GetSystemStats() (map[string]interface{}, error) {
	ctx := a.ctx

	req := &service.StatisticsReq{
		Type: "overview",
	}
	result, err := service.DataQuery.GetStatistics(ctx, req)
	if err != nil {
		g.Log().Error(ctx, "获取统计信息失败:", err)
		return nil, err
	}

	return map[string]interface{}{
		"code":    0,
		"message": "success",
		"data":    result,
	}, nil
}

// TestConnection 测试连接
func (a *App) TestConnection() string {
	return "连接正常"
}

// ShowNotification 显示通知（桌面应用专用）
func (a *App) ShowNotification(title, message string) {
	g.Log().Infof(a.ctx, "通知: %s - %s", title, message)
}

// GetDatabasePath 获取数据库路径
func (a *App) GetDatabasePath() string {
	config := g.Cfg()
	dbPath := config.MustGet(a.ctx, "database.default.link", "./data/goldtree.db").String()
	return dbPath
}

// GetServerStatus 获取服务器状态
func (a *App) GetServerStatus() map[string]interface{} {
	return map[string]interface{}{
		"status": "running",
		"mode":   "desktop",
		"database": map[string]interface{}{
			"type": "SQLite",
			"path": a.GetDatabasePath(),
		},
	}
}
